{% extends 'base_pages/base.html' %}

{% block title %}
{{_("Host Machines")}}
{% endblock %}

{% block header %}
<h1>{{_("Host Machines")}}</h1>
{% endblock %}

{% block content %}


<body>
    <!-- < 根据 baseapp.py 中的 routes 模板变量创建一系列超链接 -->

    <div style="position: absolute; top: 10px; right: 10px;">
        <span>{{ username }}</span>
        <button onclick="confirmLogout()">{{ _("Logout") }}</button>
    </div>

    <button onclick="openAddUserModal()">Add User</button>
    <table id="userTable" border="1">
        <thead>
            <tr>
                <th>Serial No.</th>
                <th>Username</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <!-- User rows will be dynamically inserted here -->
        </tbody>
    </table>

    <!-- Add User Modal -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddUserModal()">&times;</span>
            <h2>Add User</h2>
            <form id="addUserForm">
                <input type="text" id="addUsername" placeholder="Username" required>
                <input type="password" id="addPassword" placeholder="Password" required>
                <button type="button" onclick="addUser()">Add User</button>
            </form>
        </div>
    </div>

    <!-- Change Password Modal -->
    <div id="changePasswordModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeChangePasswordModal()">&times;</span>
            <h2>Change Password</h2>
            <form id="changePasswordForm">
                <input type="hidden" id="userId">
                <input type="password" id="newPassword" placeholder="New Password" required>
                <button type="button" onclick="changePassword()">Change Password</button>
            </form>
        </div>
    </div>

    <script>
        // Function to open the Add User modal
        function openAddUserModal() {
            document.getElementById("addUserModal").style.display = "block";
        }

        // Function to close the Add User modal
        function closeAddUserModal() {
            document.getElementById("addUserModal").style.display = "none";
        }

        // Function to add a new user via AJAX
        function addUser() {
            const username = document.getElementById("addUsername").value;
            const password = document.getElementById("addPassword").value;

            apiFetch('/add_user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            }).then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    alert('Failed to add user');
                }
            }).catch(error => {
                console.error('Error:', error);
                alert('Failed to add user');
            });
        }

        // Function to open the Change Password modal
        function openChangePasswordModal(userId) {
            document.getElementById("userId").value = userId;
            document.getElementById("changePasswordModal").style.display = "block";
        }

        // Function to close the Change Password modal
        function closeChangePasswordModal() {
            document.getElementById("changePasswordModal").style.display = "none";
        }

        // Function to change the user's password via AJAX
        function changePassword() {
            const userId = document.getElementById("userId").value;
            const newPassword = document.getElementById("newPassword").value;

            apiFetch(`/update_user/${userId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    password: newPassword
                })
            }).then(response => {
                if (response.ok) {
                    console.log("Password changed successfully");
                } else {
                    response.json().then(
                        respJsonData => {
                            console.log(JSON.stringify(respJsonData))
                            alert(respJsonData.error);
                        }
                    )

                }
            }).catch(error => {
                console.error('Error:', error);
                alert('Failed to change password');
            });
        }

        // Function to fetch and display all users
        function fetchUsers() {
            apiFetch('/get_all_users')
                .then(response => response.json())
                .then(data => {
                    const userTableBody = document.querySelector("#userTable tbody");
                    userTableBody.innerHTML = ""; // Clear existing rows
                    data.users.forEach((user, index) => {
                        const row = document.createElement("tr");
                        row.innerHTML = `
                            <td>${index + 1}</td>
                            <td>${user.username}</td>
                            <td>
                                <button onclick="openChangePasswordModal(${user.id})">Change Password</button>
                            </td>
                        `;
                        userTableBody.appendChild(row);
                    });
                })
                .catch(error => { console.error('Error fetching users:', error); console.log(error) });
        }

        // Call fetchUsers when the page loads
        window.onload = fetchUsers;
    </script>
    {% endblock %}